package com.hdu.xxl_job_client.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.Optional.ofNullable;


public class SimpleHttpClient {

    private static final HttpClient HTTP_CLIENT = new HttpClient();
    private static final Logger logger = LoggerFactory.getLogger(SimpleHttpClient.class);
    private static final String HTTPS_PREFIX = "https://";
    private static final String HTTP_PREFIX = "http://";
    private static final String COOKIE = "cookie";
    private static final String POST_FORM_CONTENT_TYPE = "application/x-www-form-urlencoded; charset=UTF-8";
    private static final Header POST_FORM_CONTENT_TYPE_HEADER = new Header("Content-Type", POST_FORM_CONTENT_TYPE);

    public static Cookie[] getPostCookies(String postUrl) {
        if (postUrl == null || (!postUrl.startsWith(HTTPS_PREFIX) && !postUrl.startsWith(HTTP_PREFIX))) {
            logger.error("Invalid or unsafe URL: {}", postUrl);
            return null;
        }

        HttpMethod postMethod = new PostMethod(postUrl);
        try {
            HTTP_CLIENT.executeMethod(postMethod);
            int statusCode = postMethod.getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                return HTTP_CLIENT.getState().getCookies();
            } else {
                String responseBodyStr = postMethod.getResponseBodyAsString();
                logger.error("getPostCookies fail, postUrl : {}, res : {} ", postUrl, responseBodyStr);
                return null;
            }
        } catch (HttpException e) {
            logger.error("HTTP exception occurred, postUrl : {}, msg: {}", postUrl, e.getMessage(), e);
        } catch (IOException e) {
            logger.error("IO exception occurred, postUrl : {}, msg: {}", postUrl, e.getMessage(), e);
        } finally {
            postMethod.releaseConnection();
        }
        logger.error("An unexpected error occurred, postUrl : {}", postUrl);
        return null;
    }
    public static JSONObject doPost(String postUrl, JSONObject requestBodyParams, String cookie) {

        PostMethod post = new PostMethod(postUrl);
        ofNullable(cookie).ifPresent(c -> post.setRequestHeader(COOKIE, c));
        post.setRequestHeader(POST_FORM_CONTENT_TYPE_HEADER);

        List<NameValuePair> pairList = new ArrayList<>();
        requestBodyParams.forEach((k, v) -> pairList.add(new NameValuePair(k, v.toString())));
        NameValuePair[] arr = pairList.toArray(new NameValuePair[0]);
        post.setRequestBody(arr);

        try {
            HTTP_CLIENT.executeMethod(post);
        } catch (HttpException e) {
            logger.error(
                    "doPost HTTP exception occurred, postUrl : {}, msg : {}, requestBodyParams : {}",
                    postUrl,
                    e.getMessage(),
                    requestBodyParams,
                    e
            );
        } catch (IOException e) {
            logger.error(
                    "doPost IOException exception occurred, postUrl : {}, msg : {}, requestBodyParams : {}",
                    postUrl,
                    e.getMessage(),
                    requestBodyParams,
                    e
            );
        }

        return readResponse(post);
    }



    private static JSONObject readResponse(HttpMethod httpMethod) {
        if (httpMethod.getStatusCode() != HttpStatus.SC_OK) {
            return new JSONObject();
        }
        try (InputStream inputStream = httpMethod.getResponseBodyAsStream();
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            return JSON.parseObject(bufferedReader.lines().collect(Collectors.joining(System.lineSeparator())));
        } catch (IOException e) {
            logger.error("读取响应失败：{}", e.getMessage(), e);
            JSONObject error = new JSONObject();
            error.put("code", HttpStatus.SC_INTERNAL_SERVER_ERROR);
            error.put("msg", "响应内容读取失败：" + e.getMessage());
            return error;
        }
    }


}
